package bma.common.netty.protobuf.server;

import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ExceptionEvent;

import bma.common.langutil.core.ExceptionUtil;
import bma.common.netty.NettyServer;
import bma.common.netty.handler.ChannelHandlerExceptionClose;
import bma.common.netty.handler.ChannelHandlerFramed;
import bma.common.netty.protobuf.core.NCHProtobufService;
import bma.common.netty.protobuf.core.NettyProtobufConfig;
import bma.common.netty.protobuf.core.PDispatcher;

public class NettyProtobufServer extends NettyServer {

	final org.slf4j.Logger log = org.slf4j.LoggerFactory
			.getLogger(NettyProtobufServer.class);

	protected NettyProtobufConfig config;
	protected PDispatcher dispatcher;

	public NettyProtobufServer() {
		super();
	}

	public PDispatcher getDispatcher() {
		return dispatcher;
	}

	public void setDispatcher(PDispatcher dispatcher) {
		this.dispatcher = dispatcher;
	}

	public NettyProtobufConfig getConfig() {
		return config;
	}

	public void setConfig(NettyProtobufConfig config) {
		this.config = config;
	}

	@Override
	protected void beforeBuildPipeline(ChannelPipeline pipeline) {
		super.beforeBuildPipeline(pipeline);
		pipeline.addLast("framed",
				new ChannelHandlerFramed(config.getMaxLength()));
		pipeline.addLast("service", new NCHProtobufService(config, dispatcher));
		pipeline.addLast("error", new ChannelHandlerExceptionClose() {
			@Override
			protected void logException(ChannelHandlerContext ctx,
					ExceptionEvent e) {
				if (log.isWarnEnabled()) {
					Throwable t = ExceptionUtil.cause(e.getCause());
					log.warn("{} error {}/{}", new Object[] {
							ctx.getChannel().getRemoteAddress(),
							t.getClass().getName(), t.getMessage() });
				}
			}
		});
	}

}
